<?php

namespace App\Http\Controllers\Api;


use App\Enums\UserTypeEnum;
use App\Http\Requests\Api\UserRequest;
use App\Http\Requests\Api\UserRoleRequest;
use App\Models\Profile;
use App\Models\User;
use App\Transformers\UserTransformer;
use Auth;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function me()
    {
        return $this->response->item(Auth::guard('api')->user(), new UserTransformer());
    }

    public function syncRoles(UserRoleRequest $request, User $user)
    {
        $user->syncRoles($request->roles);
        return $this->response->item($user, new UserTransformer());
    }

    public function index(Request $request, User $user)
    {
        $query = $user->query();
        if ($username = $request->username) {
            $query->name($username);
        }
        if ($name = $request->name) {
            $query->whereHas('profile', function ($query) use ($name) {
                $query->name($name);
            });
        }
        $users = $query->type(UserTypeEnum::TEACHER)->paginate(15);

        return $this->response->paginator($users, new UserTransformer());
    }

    public function store(UserRequest $request, User $user)
    {
        $user->name = $request->name;
        $user->phone = $request->phone;
        $user->is_active = $request->is_active;
        $user->type = UserTypeEnum::TEACHER;
        $user->save();

        $profile = new Profile($request->profile);
        $user->profile()->save($profile);

        $roles = $request->roles;
        $user->syncRoles($roles);
        return $this->response->item($user, new UserTransformer())
            ->setStatusCode(201);
    }

    public function update(Request $request, User $user)
    {
        $user->name = $request->name;
        $user->phone = $request->phone;
        $user->is_active = $request->is_active;
        $user->profile->name = $request->profile['name'];
        $user->profile->gender = $request->profile['gender'];
        $user->profile->desc = $request->profile['desc'];

        $user->save();
        $user->profile()->save($user->profile);

        $roles = $request->roles;
        $user->syncRoles($roles);
        return $this->response->item($user, new UserTransformer());
    }

    public function destroy(User $user)
    {
        $user->roles()->detach();
        $user->delete();
        return $this->response->noContent();
    }
}
